package com.campus.service.impl;

import com.campus.common.Result;
import com.campus.entity.CommentLikes;
import com.campus.entity.Comments;
import com.campus.entity.CommentDetailDTO;
import com.campus.mapper.CommentLikesMapper;
import com.campus.mapper.CommentsMapper;
import com.campus.service.CommentService;
import com.campus.utils.SnowFlakeUtil;
import com.campus.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentsMapper commentsMapper;

    @Autowired
    private CommentLikesMapper commentLikesMapper;

    @Autowired
    private TokenUtils tokenUtils;

    @Override
    public Result createComment(String token, String postId, Comments comment) {
        try {
            // 从token中解析用户信息
            com.campus.entity.Users currentUser = tokenUtils.getCurrentUser(tokenUtils.getToken(token));
            if (currentUser == null) {
                return Result.err(401, "用户未登录");
            }
            
            // 设置评论基本信息
            comment.setCommentId(SnowFlakeUtil.getId() + "");
            comment.setPostId(postId);
            comment.setUserId(currentUser.getUserId());
            comment.setCreateTime(new Date());
            comment.setUpdateTime(new Date());
            comment.setStatus(true); // 默认状态为有效
            comment.setLikesCount(0);
            comment.setRepliesCount(0);
            
            // 打印调试信息
            System.out.println("创建评论: " + comment.getCommentId() + 
                             ", postId: " + comment.getPostId() + 
                             ", parentId: " + comment.getParentId() + 
                             ", userId: " + comment.getUserId());
            
            // 保存评论
            int result = commentsMapper.createComment(comment);
            if (result > 0) {
                return Result.ok("评论发表成功");
            } else {
                return Result.err(500, "评论发表失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(500, "评论发表异常: " + e.getMessage());
        }
    }

    @Override
    public Result getCommentsByPostId(String postId) {
        try {
            List<CommentDetailDTO> comments = commentsMapper.getCommentsByPostId(postId);
            
            // 打印调试信息
            System.out.println("查询到的评论数量: " + comments.size());
            for (CommentDetailDTO comment : comments) {
                System.out.println("评论ID: " + comment.getCommentId() + 
                                 ", ParentId: " + comment.getParentId() + 
                                 ", 内容: " + comment.getContent());
            }
            
            // 构建评论树结构
            List<CommentDetailDTO> rootComments = new ArrayList<>();
            Map<String, CommentDetailDTO> commentMap = new HashMap<>();
            
            // 先建立所有评论的映射
            for (CommentDetailDTO comment : comments) {
                commentMap.put(comment.getCommentId(), comment);
                // 初始化回复列表
                if (comment.getReplies() == null) {
                    comment.setReplies(new ArrayList<>());
                }
            }
            
            // 构建树结构
            for (CommentDetailDTO comment : comments) {
                if (comment.getParentId() != null && !comment.getParentId().isEmpty()) {
                    // 这是一个回复评论，将其添加到父评论的回复列表中
                    CommentDetailDTO parentComment = commentMap.get(comment.getParentId());
                    if (parentComment != null) {
                        parentComment.getReplies().add(comment);
                        System.out.println("将评论 " + comment.getCommentId() + " 添加到父评论 " + comment.getParentId() + " 的回复列表中");
                    } else {
                        System.out.println("未找到父评论: " + comment.getParentId());
                    }
                } else {
                    // 这是一个顶级评论
                    rootComments.add(comment);
                    System.out.println("添加顶级评论: " + comment.getCommentId());
                }
            }
            
//
            return Result.ok(rootComments);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(500, "获取评论列表异常: " + e.getMessage());
        }
    }

    @Override
    public Result likeComment(String token, String commentId) {
        try {
            // 从token中解析用户信息
            com.campus.entity.Users currentUser = tokenUtils.getCurrentUser(tokenUtils.getToken(token));

            if (currentUser == null) {
                return Result.err(401, "用户未登录");
            }

            // 检查评论是否存在
            Comments comment = commentsMapper.getCommentById(commentId);
            if (comment == null) {
                return Result.err(404, "评论不存在");
            }

            // 检查用户是否已经点赞
            CommentLikes existingLike = commentLikesMapper.selectByCommentIdAndUserId(commentId, currentUser.getUserId());
            if (existingLike != null) {
                return Result.ok(1); // 已经点赞
            }

            // 创建点赞记录
            CommentLikes commentLike = new CommentLikes();
            commentLike.setLikeId(SnowFlakeUtil.getId() + "");
            commentLike.setCommentId(commentId);
            commentLike.setUserId(currentUser.getUserId());
            commentLike.setCreateTime(new Date());

            int result = commentLikesMapper.insert(commentLike);
            if (result > 0) {
                // 增加评论的点赞数
                commentsMapper.increaseLikesCount(commentId);
                return Result.ok(1); // 点赞成功
            } else {
                return Result.err(500, "点赞失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(500, "点赞异常: " + e.getMessage());
        }
    }

    @Override
    public Result unlikeComment(String token, String commentId) {
        try {
            // 从token中解析用户信息
            com.campus.entity.Users currentUser = tokenUtils.getCurrentUser(tokenUtils.getToken(token));

            if (currentUser == null) {
                return Result.err(401, "用户未登录");
            }

            // 检查评论是否存在
            Comments comment = commentsMapper.getCommentById(commentId);
            if (comment == null) {
                return Result.err(404, "评论不存在");
            }

            // 删除点赞记录
            int result = commentLikesMapper.deleteByCommentIdAndUserId(commentId, currentUser.getUserId());
            if (result > 0) {
                // 减少评论的点赞数
                commentsMapper.decreaseLikesCount(commentId);
                return Result.ok(0); // 取消点赞成功
            } else {
                return Result.ok(0); // 没有点赞记录，直接返回
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(500, "取消点赞异常: " + e.getMessage());
        }
    }

    @Override
    public Result checkCommentLikeStatus(String token, String commentId) {
        try {
            // 从token中解析用户信息
            com.campus.entity.Users currentUser = tokenUtils.getCurrentUser(tokenUtils.getToken(token));

            if (currentUser == null) {
                return Result.err(401, "用户未登录");
            }

            // 检查评论是否存在
            Comments comment = commentsMapper.getCommentById(commentId);
            if (comment == null) {
                return Result.err(404, "评论不存在");
            }

            // 检查用户是否已经点赞
            CommentLikes existingLike = commentLikesMapper.selectByCommentIdAndUserId(commentId, currentUser.getUserId());
            if (existingLike != null) {
                return Result.ok(1); // 已经点赞
            } else {
                return Result.ok(0); // 未点赞
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(500, "检查点赞状态异常: " + e.getMessage());
        }
    }
}